﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Configuration;
using System.Data;
using System.Windows;
using System.Windows.Media.Imaging;
using VIA.Applications;
using VIA.Presentation.View;
using VIA.Presentation;
using Microsoft.Extensions.DependencyInjection;
using VIA.SiMoJi.Domain;

namespace VIA.SiMoJi.Management
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        IHost _host;
        IAbpApplicationWithExternalServiceProvider _application;
        internal static string AppName = "自动撕膜设备";
        ILogger _logger;
        Mutex mutex;
        bool _isRunning = false;

        public App()
        {
            mutex = new Mutex(false, AppName);
            _isRunning = !mutex.WaitOne(0);
            if (_isRunning)
            {
                MessageBox.Show($"{AppName}程序已经在运行中，不可重复运行!");
                Environment.Exit(0);
            }
        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            if (_isRunning) return;
            var loadingView = new StartupLoadingView();
            loadingView.Title = AppName;
            loadingView.Show();
            loadingView.Activate();
            _host = CreateHostBuilder();
            _application = _host.Services.GetRequiredService<IAbpApplicationWithExternalServiceProvider>();
            _logger = _host.Services.GetRequiredService<ILogger<App>>();
            _logger.LogInformation("App Startup");
            await _host.StartAsync();
            try
            {
                _application.Initialize(_host.Services);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "启动初始化过程中发生异常");
                MessageBox.Show($"应用程序启动初始化过程中发生异常:{ex.Message}\n异常详细已写入日志\n点击确定后退出");
                loadingView.Close();
                Environment.Exit(-1);
            }
            var shellService = _host.Services.GetRequiredService<IShellService>();
            shellService.ShellWindow.Title = AppName;
            shellService.ShellWindow.Icon = null;
            shellService.ShellWindow.Icon = new BitmapImage(new Uri("./logo.ico", UriKind.RelativeOrAbsolute));
            Current.MainWindow = shellService.ShellWindow;
            loadingView.Close();
            Current.MainWindow.Show();
            Current.MainWindow.Activate();
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            _logger.LogError(e.Exception, e.Exception.Message);
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            _logger.LogError(ex, ex?.Message);
        }

        private IHost CreateHostBuilder()
        {
            return Host
                .CreateDefaultBuilder(null)
                .UseAutofac()
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddApplication<StartupModule>();
                }).Build();
        }

        protected override async void OnExit(ExitEventArgs e)
        {
            await _host.Services.GetService<ICalcTimeService>().Save();
            _application.Shutdown();
            await _host.StopAsync();
            _host.Dispose();
        }
    }

}
